package com.junglone.gateway.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import reactor.core.publisher.Mono;

/**
 * Description:
 *
 * @author junglone: <a href="mailto:cjlnzb@hotmail.com">cjlnzb@hotmail.com</a>
 * @since 2020/09/24 17:02
 */
@Component
public class MyCustomGlobalFilter implements GlobalFilter {

    private static final Logger LOGGER = LoggerFactory.getLogger(MyCustomGlobalFilter.class);

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {

        String strAuth = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
        LOGGER.info("received AUTHORIZATION == {}", strAuth);

        // 设置请求头并流转到下游服务
        ServerHttpRequest mutableReq = exchange.getRequest().mutate()
                // 使用 add 方法设置请求头, 不会覆盖原本已有的值
                .headers(httpHeaders -> httpHeaders.set(HttpHeaders.AUTHORIZATION, "Modified MyCustomGlobalFilter"))
                .build();
        ServerWebExchange mutableExchange = exchange.mutate().request(mutableReq).build();

        return chain.filter(mutableExchange);
    }

}
